﻿using MathTutorPro.DAL;
using MathTutorPro.Data.Entities;
using MathTutorPro.Models.Requests;
using MathTutorPro.Models.Responses;
using MathTutorPro.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;

namespace MathTutorPro.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    //[Authorize(Roles = "Teacher")]
    public class ClassController : ControllerBase
    {
        private readonly IClassService _classService;

        public ClassController(IClassService classService)
        {
            _classService = classService;
        }

        // GET: api/class/my-classes
        //获取当前登录教师创建的所有班级列表
        [HttpGet("my-classes")]
        public async Task<IActionResult> GetMyClasses()
        {
            var teacherId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var classes = await _classService.GetClassByUserAsync(teacherId);
            return Ok(new { code = 20000, data = classes });
        }

        [HttpGet]
        public async Task<IActionResult> GetClasses()
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            if (string.IsNullOrEmpty(userId))
                return Unauthorized(new { code = 401, message = "未登录" });

            var classes = await _classService.GetClassByUserAsync(userId);
            var response = classes.Select(c => new ClassResponse
            {
                ClassId = c.Id,
                ClassName = c.ClassName,
                StudentCount = c.ClassDetails.Count
            });

            return Ok(new { code = 20000, data = response });
        }

        // POST: api/class
        //创建新班级
        [HttpPost]
        public async Task<IActionResult> CreateClass([FromBody] ClassCreateRequest request)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            if (string.IsNullOrEmpty(userId))
                return Unauthorized(new { code = 401, message = "未登录" });

            var classId = await _classService.CreateClassAsync(userId, request.ClassName);
            return Ok(new { code = 20000, data = new { classId } });
        }
    }

}
